﻿using ConfigurationUtility;
using DataModel;
using LogCentre;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace TSC
{

    public class TempratureManager
    {
        public event CableDisabledEventHandler CableDisabledEvent;
        private TempratureRecord record;
        ModbusStation mainStation;
        private ConfigUtility configUtility;
        private int ConnectInterval;


        public TempratureManager(ConfigUtility _configUtility)
        {
            configUtility = _configUtility;
            //taskFactory = _taskFactory;
            ConnectInterval = Convert.ToInt32(configUtility.GetValue(Constant_Fields.ConnectInterval));

            //
            record = new TempratureRecord();
            //
            mainStation = new ModbusStation(_configUtility, ConnectInterval);
            mainStation.CableDisabledEvent += MainStation_CableDisabledEvent;
            //highAreaStation.DataReceivedEvent += MainStation_DataReceivedEvent;
            mainStation.ConnectionFailureEvent += MainStation_ConnectionFailureEvent;//
            mainStation.CloseEvent += MainStation_CloseEvent;//
        }

        private void MainStation_CableDisabledEvent(byte CableId, bool valid)
        {
            //一方面要写入数据库。
            //另一方面要告诉主界面设置为false
            record.AddAlarmTo3D(4, "感温电缆" + CableId, "温度读取故障。");
            CableDisabledEvent?.Invoke(CableId, valid);
        }

        private void MainStation_CloseEvent(int DeviceId)
        {
            //需要将所有的数据设置为isEnable设置为false
            //record.SetAllCableDisabled();
            if (GlobalVar.disableCache)
                record.AddAlarmTo3D(4, "感温设备" + DeviceId + "#", "感温电缆连接关闭！");

            Task.Run(() => ReStart());
        }

        private void ReStart()
        {
            Thread.Sleep(ConnectInterval);
            MainLog.Info("感温设备重新启动连接。", true);
            mainStation.Start();
        }

        private void MainStation_ConnectionFailureEvent(int DeviceId)
        {
            if (GlobalVar.connectioinCache)
                record.AddAlarmTo3D(4, "感温设备" + DeviceId + "#", "感温设备连接中断！");

            Task.Run(() => ReStart());
        }

        public void Start()
        {
            MainLog.Info("感温设备启动连接。", true);
            mainStation.Start();
        }

        public void Stop()
        {
            mainStation.Dispose();
        }
    }
}
